package com.smg.community.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javacommon.base.BaseRestSpringController;
import javacommon.util.FileUtil;

import com.google.gson.Gson;
import com.smg.community.model.SmgTopic;
import com.smg.community.util.ImageUtil;
import com.smg.community.util.ImageUtil2;
import com.smg.community.util.ProjectUtil;

/**
 * @author user
 * 处理图片上传的类
 */
@Controller
@RequestMapping("/image")
public class ImageController  extends BaseRestSpringController<SmgTopic,java.lang.Integer>{

		/**
		 * 上传图片,返回图片的时间路径
		 *  根据 from 处理其他逻辑
		 * 如 2012-12-3/21234235.jpg
		 * @throws IOException 
		 */
		@RequestMapping(value="/uploadimage")
		public void uploadImage(ServletRequest request,HttpServletResponse response) throws IOException{
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("utf-8");
			Writer out = response.getWriter();
			String path =  ProjectUtil.imageUploadPath;  
			String subfolder = request.getParameter("subfolder");
				//path = "E:\\ddmap\\image\\crm\\";
			if ( subfolder != null && !subfolder.equals("")){
				path = path  + "/" + subfolder;
			}
			path = path +"/";
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String filename = request.getParameter("filename");
			// 通过编辑器上传的图片默认的filename
			if ( filename == null ||filename.equals("")){
					filename = "imgFile";
			}
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
					.getFile(filename);
			long fileSize = file.getSize();
			String maxSize = request.getParameter("maxsize");
			if(maxSize !=null ){
				float max = Float.parseFloat(maxSize)*1024*1024;
				if(fileSize >   max){
					writeMessage(out, "toolagre");
					return ;
				}
			}
			SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
			String dateString = simpleFormat.format(new Date());
			String imagepath =  path + dateString;
			/*
			File fdir = new File(imagepath);
			if (!fdir.exists()){
				fdir.mkdirs();
			}
			String fileName = file.getFileItem().getName();
			String ext = fileName.substring(fileName.lastIndexOf("."));
			String newFileName = dateString + "-" + System.currentTimeMillis()
					+ ext;
			File f = new File(imagepath + "/" + newFileName);
			FileOutputStream fos = null;
			fos = new FileOutputStream(f);
			fos.write(file.getBytes());
			fos.close();*/ 
			long timestamp = System.currentTimeMillis(); 
			String savepath = FileUtil.uploads(multipartRequest,imagepath,new SimpleDateFormat("HHmmssSSS").format(timestamp),filename);
			// 判断是否需要缩略图片
			String smallwidthStr = request.getParameter("smallwidth");
			String smallheightStr = request.getParameter("smallheight");
			String extname  = ""; 
			if ( filename.equals("imgFile")){
				smallwidthStr = "650";
				smallheightStr = "650";
			}
			CommonsMultipartFile  orginalFile = (CommonsMultipartFile) multipartRequest.getFile(filename);
			ImageUtil2 util = new ImageUtil2();
			FileItem fileItem = orginalFile.getFileItem();
			extname = fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
			if ( smallwidthStr!=null && !smallwidthStr.equals("") && smallheightStr!=null && !"".equals(smallheightStr)){
				try {
					int smallwidth = Integer.parseInt(smallwidthStr);
					int smallheight = Integer.parseInt(smallheightStr); 
			  		try {
						if(orginalFile != null && !orginalFile.isEmpty()){
						}
			  		}  catch (Exception e){
			  			e.printStackTrace();
			  		}
			  		File f = new File (path + "650/"+dateString+"/");
			  		if (f.exists() == false){
			  			System.out.println(f.mkdirs());
			  		}
					util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/650/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, smallwidth, smallheight);
				}catch(Exception e){
					e.printStackTrace();
				}
				
			}
			File f =  new File (path + "130/"+dateString+"/");
	  		if (f.exists() == false){
	  			System.out.println(f.mkdirs());
	  		}
			// 存1个 100 × 100 的
			util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/130/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, 130, 130);
			f = new File (path + "203/"+dateString+"/");
	  		if (f.exists() == false){
	  			System.out.println(f.mkdirs());
	  		}
			// 存1个 400 × 400 的
			util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/203/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, 203, 203);
			System.out.println(savepath);
			//writeMessage(out, savepath.substring(savepath.indexOf("uploadimage/") + 12));
			if ( smallwidthStr!=null && !smallwidthStr.equals("") && smallheightStr!=null && !"".equals(smallheightStr)){
				savepath =  path + "650/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname;
			}else{
				savepath =  path +dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname;
			}
			Map<String,Object> param = new HashMap<String,Object>();
			Gson gson = new Gson();
			param.put("error", 0);
			String imagePrefix = ProjectUtil.imagePrefix;
			param.put("url", imagePrefix + savepath.substring(savepath.indexOf("images/") ));
			out.write( gson.toJson(param));
			out.close();
		}
		
		public static void main(String[] args) throws UnsupportedEncodingException{
		 System.out.println(	new SimpleDateFormat("HHmmssSSS").format(System.currentTimeMillis()));
		}
}
